from fastapi import HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi import Request
from schemas.response import ResponseModel

class CustomException(Exception):
    def __init__(
        self,
        code: int,
        message: str,
        status_code: int = 200,
    ):
        self.code = code
        self.message = message
        self.status_code = status_code
        super().__init__(message)

class ParameterError(CustomException):
    def __init__(self, message: str = "参数错误"):
        super().__init__(code=400, message=message)

class UnauthorizedError(CustomException):
    def __init__(self, message: str = "未授权"):
        super().__init__(code=401, message=message)

class ForbiddenError(CustomException):
    def __init__(self, message: str = "禁止访问"):
        super().__init__(code=403, message=message)

class NotFoundError(CustomException):
    def __init__(self, message: str = "资源不存在"):
        super().__init__(code=404, message=message)

# 添加验证错误处理函数
def format_validation_error(errors):
    """格式化验证错误信息"""
    error_messages = []
    for error in errors:
        field = " -> ".join(str(x) for x in error["loc"])
        message = error["message"]
        error_messages.append(f"{field}: {message}")
    return "; ".join(error_messages)

async def validation_exception_handler(request: Request, exc: RequestValidationError):
    """处理请求参数验证错误"""
    return JSONResponse(
        status_code=200,
        content=ResponseModel(
            code=422,
            message=format_validation_error(exc.errors()),
            data=None
        ).model_dump()
    ) 